﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace OpenQuarters.WebQuarters.Core
{
    [Serializable]
    public class LimitedDictionary<T1, T2> : Utils.FriendlyDictionary<T1, T2>
    {
        private List<T1> keyAddedOrder = new List<T1>();

        private int limit = -1;

        public int Limit
        {
            get { return limit; }
            set { limit = value; }
        }

        public LimitedDictionary()
            : base()
        {
        }

        public LimitedDictionary(int limit)
            : base()
        {
            this.Limit = limit;
        }

        public LimitedDictionary(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        public new T2 this[T1 key]
        {
            get
            {
                return base[key];
            }
            set
            {

                if (!keyAddedOrder.Contains(key))
                {
                    keyAddedOrder.Remove(key);
                }
                base[key] = value;
                keyAddedOrder.Insert(0, key);
                if (keyAddedOrder.Count > this.Limit)
                {
                    // Remove oldest item
                    base.Remove(keyAddedOrder.Last());
                    keyAddedOrder.Remove(keyAddedOrder.Last());
                }
            }
        }
    }
}
